package handler

import (
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"io"
	"net/http"
	"os"
	"renting-demo/api/internal/logic"
	"renting-demo/api/internal/svc"
	"renting-demo/api/internal/types"
	"strconv"
	"strings"
	"time"
)

func UserEditAvatarHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		img, body, _ := r.FormFile("imgs")
		//验证图片大小
		if body.Size > 1024*1024*2 {
			httpx.ErrorCtx(r.Context(), w, errors.New("图片过大"))
			return
		}
		fix := strings.Split(body.Filename, ".")[len(strings.Split(body.Filename, "."))-1]
		fixAll := []string{"jpg", "png", "gif", "jpeg"}
		//验证图片格式
		if !InArray(fixAll, fix) {
			httpx.ErrorCtx(r.Context(), w, errors.New("图片格式错误"))
			return
		}
		//md5加密
		h := md5.New()
		io.WriteString(h, strconv.Itoa(int(time.Now().Unix())))
		fileName := fmt.Sprintf("%x", h.Sum(nil))

		filePath := "./internal/uploads/" + fileName + "." + fix
		fmt.Println(filePath)
		//打开文件
		file, _ := os.Create(filePath)
		//复制图片
		io.Copy(file, img)
		//七牛云上传
		//url, err := public.QiNiuYun(filePath, fileName)
		//if err != nil {
		//	httpx.ErrorCtx(r.Context(), w, errors.New("七牛云上传有误:"+err.Error()))
		//	return
		//}
		//重新设置 图片的值为 七牛云外链
		r.Form.Set("imgs", "www.adsfksjgk.jpg")

		var req types.UserEditAvatarReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewUserEditAvatarLogic(r.Context(), svcCtx)
		resp, err := l.UserEditAvatar(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
func InArray(s []string, substr string) bool {
	for _, v := range s {
		if v == substr {
			return true
		}
	}
	return false
}
